package com.maltys.controller;

import com.maltys.redission.raw.RawRedisLockV1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author malty
 */
@RestController
@RequestMapping("/test")
public class RawRedisLockTestController {

    private final AtomicInteger atomicInteger = new AtomicInteger(1);
    @Autowired
    RawRedisLockV1 rawRedisLock;

    @RequestMapping("/v1/redis/lock")
    public void testRedisLock() {
        atomicInteger.set(1);
        Runnable runnable = () -> {
            String name = "t" + atomicInteger.getAndIncrement();
            String uuid = UUID.randomUUID().toString();
            try {
                while (true) {
                    if (rawRedisLock.tryLock(name, uuid, 100, TimeUnit.SECONDS)) {
                        System.out.println(name + " get lock");
                        System.out.println(name + " working...");
                        break;
                    } else {
                        System.out.println(name + " get lock failed -----------");

                        Thread.sleep(10);

                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        };
        for (int i = 0; i < 100; i++) {
            new Thread(runnable).start();
        }
    }

    @RequestMapping("/v1/redis/unlock")
    public void testRedisReleaseLock() {
        atomicInteger.set(1);
        for (int i = 0; i < 100; i++) {
            Runnable runnable = () -> {
                String name = "t" + atomicInteger.getAndIncrement();
                String s = rawRedisLock.getStringRedisTemplate().opsForValue().get(name);
                if (!ObjectUtils.isEmpty(s)) {
                    rawRedisLock.releaseLock(name, s);
                }
            };
            new Thread(runnable).start();
        }
    }
}
